package com.itheima.controller.admin;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/checkgroup")
@Slf4j
@Api(tags = "检查组管理")
@RequiredArgsConstructor
public class CheckgroupController {
    private final CheckGroupService checkgroupService;

    /**
     * 添加检查组
     *
     * @param checkGroup
     */
    @PostMapping("/add")
    @ApiOperation("添加检查组")
    public Result addCheckGroup(
            @RequestBody CheckGroup checkGroup,
            @RequestParam("checkitemIds") String checkitemIdsStr  // 接收查询字符串参数
    ) {
        log.info("添加检查组:{}", checkGroup);
        log.info("checkitemIdsStr: {}", checkitemIdsStr);
        // 将字符串转换为 Integer 列表
        List<Integer> checkItemIds = new ArrayList<>();
        if (checkitemIdsStr != null && !checkitemIdsStr.isEmpty()) {
            String[] idsArray = checkitemIdsStr.split(",");
            for (String idStr : idsArray) {
                try {
                    int id = Integer.parseInt(idStr.trim());
                    checkItemIds.add(id);
                } catch (NumberFormatException e) {
                    log.error("Invalid checkItemId: {}", idStr, e);
                }
            }
        }
        Result result = new Result();
        try {
            checkgroupService.addcheckGroup(checkGroup, checkItemIds);
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(MessageConstant.ADD_CHECKGROUP_FAIL);
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.ADD_CHECKGROUP_SUCCESS);
        return result;
    }


    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    @ApiOperation("检查组分页查询")
    public PageResult page(@RequestBody QueryPageBean queryPageBean) {
        log.info("检查组分页查询：{}", queryPageBean);
        return checkgroupService.pageQuery(queryPageBean);
    }

    /**
     * 删除检查组
     *
     * @param id
     * @return
     */
    @GetMapping("/deleteById")
    @ApiOperation("检查组删除")
    public Result addCheckGroup(Long id) {
        log.info("删除id是：{}", id);
        Result result = new Result();
        try {
            checkgroupService.deletecheckGroup(id);
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.DELETE_CHECKGROUP_SUCCESS);
        return result;
    }

    /**
     * 修改检查组
     *
     * @param checkGroup
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("检查组修改")
    public Result updateCheckGroup(
            @RequestBody CheckGroup checkGroup,
            @RequestParam("checkitemIds") String checkitemIdsStr  // 添加注解，参数名与接口文档一致
    ) {
        // 验证 id 是否有效
        if (checkGroup.getId() == null) {
            return new Result(false, MessageConstant.EDIT_CHECKGROUP_FAIL, "ID 不能为空");
        }
        log.info("修改检查组:{}", checkGroup);
        log.info("checkitemIds: {}", checkitemIdsStr);  // 日志参数名同步修改


        List<Integer> checkItemIds = convertToIntegerList(checkitemIdsStr);


        Result result = new Result();
        try {
            checkgroupService.updatecheckGroup(checkGroup, checkItemIds);
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(MessageConstant.EDIT_CHECKGROUP_FAIL);
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.EDIT_CHECKGROUP_SUCCESS);
        return result;
    }


    /**
     * 查询所有检查组
     *
     * @return
     */
    @GetMapping("/findAll")
    @ApiOperation("查询所有检查组")
    public Result findByAllCheckGroup() {
        Result result = new Result();
        try {
            List<CheckItem> items = checkgroupService.findByAllcheckGroup();
            result.setData(items);
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(MessageConstant.QUERY_CHECKGROUP_FAIL);
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.QUERY_CHECKGROUP_SUCCESS);
        return result;
    }

    /**
     * 根据id查询检查组
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    @ApiOperation("根据id查询检查组")
    public Result findByIdCheckGroup(Long id) {
        Result result = new Result();
        try {
            List<CheckGroup> items = checkgroupService.findByIdcheckGroup(id);
            if(items != null && !items.isEmpty()) {
                // 返回第一个对象而不是列表
                result.setData(items.get(0));
            } else {
                throw new Exception(MessageConstant.QUERY_CHECKGROUP_FAIL);
            }
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.QUERY_CHECKGROUP_SUCCESS);
        return result;
    }

    /**
     * 根据id查询检查组
     *
     * @param setmealId
     * @return
     */
    @GetMapping("/findCheckGroupIdsBySetmealId")
    @ApiOperation("根据id查询检查组")
    public Result findCheckGroupIdsBySetmealId(Long setmealId) {

        Result result = new Result();
        try {
            List<Long> ids = checkgroupService.findCheckGroupIdsBySetmealId(setmealId);
            result.setData(ids);
        } catch (Exception e) {
            result.setFlag(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setFlag(true);
        result.setMessage(MessageConstant.QUERY_CHECKGROUP_SUCCESS);
        return result;
    }
    // 添加通用ID转换方法
    private List<Integer> convertToIntegerList(String idsStr) {
        List<Integer> ids = new ArrayList<>();
        if (idsStr != null && !idsStr.isEmpty()) {
            for (String id : idsStr.split(",")) {
                try {
                    ids.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    log.error("无效的ID格式: {}", id);
                }
            }
        }
        return ids;
    }
}


